package com.example.system.security.service;

import com.example.common.exception.CustomException;
import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

@Service
@RequiredArgsConstructor
public class CaptchaService {
    
    private final Producer captchaProducer;
    
    @Resource(name = "stringRedisTemplate")
    private final StringRedisTemplate redisTemplate;
    
    public Map<String, String> generateCaptcha() {
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);
        String uuid = UUID.randomUUID().toString();
        
        redisTemplate.opsForValue().set("captcha:" + uuid, captchaText, 5, TimeUnit.MINUTES);
        
        String base64Image;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", out);
            base64Image = Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate captcha image", e);
        }
        
        return Map.of(
            "uuid", uuid,
            "img", "data:image/jpeg;base64," + base64Image
        );
    }
    
    public boolean validateCaptcha(String uuid, String code) {
        String realCode = redisTemplate.opsForValue().get("captcha:" + uuid);
        if (realCode == null) {
            throw new CustomException(400, "Captcha expired");
        }
        if (!realCode.equalsIgnoreCase(code)) {
            throw new CustomException(400, "Captcha invalid");
        }
        redisTemplate.delete("captcha:" + uuid);
        return true;
    }
}
